package v2

// 已弃用

import (
	"fmt"

	modelJielong "youdu/model/jielong"

	"github.com/go-gormigrate/gormigrate/v2"
	"gorm.io/gorm"
)

var triggerNamePrefix = "trg_update_users_count_"

// 实现接龙人数自动更新
var AddTriggerUpdateUsersCount = gormigrate.Migration{
	ID: "v2.AddTriggerUpdateUsersCount",
	Migrate: func(tx *gorm.DB) error {
		tb1 := modelJielong.Lists{}.TableName()
		tb2 := modelJielong.ListUsers{}.TableName()
		return tx.Exec(fmt.Sprintf(`
			CREATE OR REPLACE TRIGGER %safter_insert
			AFTER INSERT ON %s
			FOR EACH ROW
			BEGIN
				UPDATE %s
				SET users_count = (SELECT COUNT(*) FROM %s WHERE list_id = :NEW.list_id)
				WHERE id = :NEW.list_id;
			END;
		`, triggerNamePrefix, tb2, tb1, tb2)).Error
	},
	Rollback: func(tx *gorm.DB) error {
		return tx.Exec(fmt.Sprintf(`
			DROP TRIGGER IF EXISTS %safter_insert;
		`, triggerNamePrefix)).Error
	},
}
